<?php

namespace App\Exports;

use App\Models\Agent;
use App\Models\IndicatorsDailySummary;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;

class AgentExport extends BaseExport implements FromQuery
{
    public function headings(): array
    {
        return [
            '代理名称',
            '等级',
            '手机号',
            '账户余额',
            '不可提余额',
            '个人业绩',
            '团队业绩',
            '上级邀请人',
            '直接邀请数',
            '间接邀请数',
            '关联合伙人',
            '标签',
            '状态',
            '加入时间',
            '登入次数',
            '最后登入时间',
            '代理性别',
            '微信',
            '生日',
            '归属地',
            '收货地址'
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();

        return [
            $this->removeUncommonWords($this->removeEmoji($row['name'])), // 代理名称
            Agent::LEVEL_MAP[$row['level']]['text'], // 等级
            $row['phone'], // 手机号
            number_format($row['balance'] / 100, 2), // 账户余额
            number_format($row['unextractable_balance'] / 100, 2), // 不可提余额
            number_format($row['personal_performance'] / 100, 2), // 个人业绩
            number_format($row['team_performance'] / 100, 2), // 团队业绩
            $this->removeUncommonWords($this->removeEmoji($row['direct_inviter']['name'] ?? '')), // 上级邀请人
            $row['number_of_direct_inviter'], // 直接邀请数
            $row['number_of_indirect_inviter'], // 间接邀请数
            $this->removeUncommonWords($this->removeEmoji($row['affiliated_partner']['name'] ?? '')), // 关联合伙人
            implode(';', array_column($row['labels'] ?? [], 'name')), // 标签
            Agent::STATUS_MAP[$row['status']], // 状态
            $row['created_at'], // 加入时间
            $row['login_frequency'], // 登入次数
            $row['last_time_of_login'], // 最后登入时间
            Agent::GENDER_CN_MAP[$row['gender']] ?? '未知', // 代理性别
            $this->removeUncommonWords($this->removeEmoji($row['wechat_number'])), // 微信
            $row['birthday'] ?? '', // 生日
            $this->removeUncommonWords($this->removeEmoji(($row['province']['name'] ?? '') . ($row['city']['name'] ?? '') . ($row['area']['name'] ?? ''))), // 归属地
            $this->removeUncommonWords($this->removeEmoji($row['address'] ?? '')), // 收货地址
        ];
    }

    public function query()
    {
        return Agent::query()
            ->with(['affiliatedPartner.partnerIdentity', 'directInviter', 'indirectInviter', 'province', 'city', 'area'])
            ->when($this->request['with_labels'] ?? true, function (Builder $builder) {
                $builder->with(['labels']);
            })
            ->when($this->request['name'] ?? '', function (Builder $builder, $name) {
                $builder->where('agents.name', 'like', "%$name%");
            })
            ->when($this->request['phone'] ?? '', function (Builder $builder, $phone) {
                $builder->where('agents.phone', 'like', "%$phone%");
            })
            ->when($this->request['level'] ?? '', function (Builder $builder, $level) {
                $builder->where('agents.level', $level);
            })
            ->when($this->request['labels'] ?? [], function (Builder $builder, $labels) {
                $builder->whereHas('labels', function (Builder $subBuilder) use ($labels) {
                    $subBuilder->whereIn('agent_labels.id', $labels);
                });
            })
            ->when($this->request['affiliated_partner'] ?? 0, function (Builder $builder, $affiliatedPartner) {
                $builder->where('agents.affiliated_partner', $affiliatedPartner);
            })
            ->when($this->request['affiliated_partner_phone'] ?? '', function (Builder $builder, $affiliatedPartnerPhone) {
                $builder->join('agents as agents_self', 'agents_self.id', '=', 'agents.affiliated_partner')
                    ->where('agents_self.phone', 'like', "%$affiliatedPartnerPhone%");
            })
            ->when($this->request['direct_inviter_phone'] ?? '', function (Builder $builder, $directInviterPhone) {
                $builder->join('agents as agents_self', 'agents_self.id', '=', 'agents.direct_inviter')
                    ->where('agents_self.phone', 'like', "%$directInviterPhone%");
            })
            ->when($this->request['indirect_inviter_phone'] ?? '', function (Builder $builder, $indirectInviterPhone) {
                $builder->join('agents as agents_self', 'agents_self.id', '=', 'agents.indirect_inviter')
                    ->where('agents_self.phone', 'like', "%$indirectInviterPhone%");
            })
            ->when($this->request['created_at_begin'] ?? '', function (Builder $builder, $createdAtBegin) {
                $builder->where('agents.created_at', '>=', $createdAtBegin);
            })
            ->when($this->request['created_at_end'] ?? '', function (Builder $builder, $createdAtEnd) {
                $builder->where('agents.created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
            })
            ->when(
                $this->request['performance_range_begin'] ?? '' && $this->request['performance_range_end'] ?? '',
                function (Builder $builder) {
                    $begin = $this->request['performance_range_begin'] ?? '';
                    $end = $this->request['performance_range_end'] ?? '';

                    $builder
                        ->select([
                            // 这里把 personal_performance 和 team_performance 去掉, 单独另外统计
                            'agents.id', 'agents.name', 'agents.phone', 'agents.level', 'agents.gender', 'agents.wechat_number', 'agents.status', 'agents.created_at',
                            'agents.number_of_direct_inviter', 'agents.direct_inviter', 'agents.balance', 'agents.unextractable_balance',
                            'agents.number_of_direct_inviter', 'agents.number_of_direct_inviter', 'agents.number_of_indirect_inviter',
                            'agents.affiliated_partner', 'agents.login_frequency', 'agents.last_time_of_login',
                            'agents.province', 'agents.city', 'agents.area', 'agents.address',
                        ])
                        ->selectSub(
                        // 个人业绩按日期范围汇总
                            \DB::table('indicators_daily_summary')
                                ->selectRaw('sum(performance_summary)')
                                ->whereBetween('day', [$begin, $end])
                                ->where('type', IndicatorsDailySummary::TYPE_AGENT)
                                ->whereRaw('agent_id = agents.id'),
                            'personal_performance'
                        )
                        ->selectSub(
                        // 团队业绩按日期范围汇总
                            \DB::table('indicators_daily_summary')
                                ->selectRaw('sum(performance_summary)')
                                ->whereBetween('day', [$begin, $end])
                                ->where('type', IndicatorsDailySummary::TYPE_TEAM)
                                ->whereRaw('agent_id = agents.id'),
                            'team_performance'
                        );
                },
                function (Builder $builder) {
                    $builder->select('agents.*');
                })
            ->when($this->request['select'] ?? [], function (Builder $builder, $select) {
                $builder->select($select);
            });
    }
}
